<?php
/**
 * Created by PhpStorm.
 * User: spatra
 * Date: 15-1-8
 * Time: 下午2:33
 */

class CallnameController extends \BaseController
{

    /**
     * 返回点名列表.
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式如下：
     * [
     *  {
     *      "id": "编号id",
     *      "name": "列表的名称",
     *      "description": "列表的描述",
     *  },
     *  //注意是个数组.....
     * ]
     */
    public function index()
    {
        $resp = Callname_List::where('creater_id', Auth::user()['id'])
            ->get();

        return Response::json($resp);
    }

    /**
     * 保存新建的点名列表，提交的字段如下：
     *  name: 列表的名称
     *  description: 列表的描述
     *  students: 列表中的学生，应该是个数组，数据的元素包含：name/description
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * 操作成功时返回：
     * {
     *      "id": "主键"
     * }
     *
     * 操作失败时：
     * {
     *      "error": "相关的错误信息"
     * }
     */
    public function store()
    {
        $name = Input::get('name', null);

        if( !$name ){
            return Response::json([
               'error' => '列表名是必填选项'
            ]);
        }

        try{
            DB::beginTransaction();
            $add = Callname_List::create([
                'creater_id' => Auth::user()['id'],
                'description' => Purifier::clean(Input::get('description', null)),
                'name' => $name
            ]);

            $storeData = Input::get('students');

            foreach($storeData as $currentStudent){
                Callname_Student::create([
                    'name'=>$currentStudent['name'],
                    'number'=>$currentStudent['number'],
                    'callname_list_id'=>$add['id']
                ]);
            }

            DB::commit();

            return Response::json([
                'id'=>$add['id']
            ]);
        }catch (Exception $err){
            DB::rollBack();
            return Response::json([
                'error'=>$err->getMessage()
            ], 500);
        }
    }

    /**
     * 对上传的Excel文件进行处理，返回对应的格式化JSON数据.
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式：
     *  [
     *      {
     *          "name": "姓名",
     *          "number": "学号"
     *      },
     *      //注意是个数组........
     *  ]
     */
    public function excel()
    {
        $validator = $this->getFileValidator(Input::all());

        if( $validator->passes() ){
            $file = Input::file('file');

            $storeData = [];
            Excel::load($file->getRealPath(), function($reader) use ( & $storeData){
                $reader->each(function($sheet)use( & $storeData){
                    $result = $this->getStoreData($sheet);
                    if( ! empty($result) ){
                        $storeData = array_merge($storeData, $result);
                    }
                });
            });

            return Response::json($storeData);
        }else{

            return Response::json([
                'error'=> $this->changeValidatorMessageToString($validator->getMessageBag())
            ], 403);
        }
    }

    /**
     * 对Excel文件的内容进行转换，得到结果的关联数组.
     *
     * @param $excelSheet
     * @return array
     */
    protected function getStoreData($excelSheet)
    {
        $inData = false;
        $numberIndex = null;
        $nameIndex = null;

        $rtnData = [];

        foreach($excelSheet as $currentRow) {

            if( $inData ){
                $tmpName = trim( (string)$currentRow[$nameIndex] );
                $tmpNumber = trim( (string)$currentRow[$numberIndex] );

                //学号和姓名都存在才录入
                if( $tmpName && $tmpNumber ){
                    //录入数据
                    array_push($rtnData, [
                        'name' => $tmpName,
                        'number' => $tmpNumber
                    ]);
                }

            }else{

                foreach($currentRow as $index=>$cell){

                    //尝试查找学号
                    if( strripos($cell, '学号') !== false ){
                        $numberIndex = $index;
                    }

                    //尝试查找姓名
                    if( strripos($cell, '姓名') !== false ){
                        $nameIndex = $index;
                    }

                    //如果都找到了就进入数据录取阶段
                    if( ! is_null($nameIndex) && ! is_null($numberIndex) ){
                        $inData = true;
                        break;
                    }
                }

                if( !$inData ){
                    $numberIndex = $nameIndex = null;
                }

            }
        }

        return $rtnData;
    }

    /**
     * 生成对excel文件进行格式和大小的校验的校验器.
     *
     * @param $postData
     * @return \Illuminate\Validation\Validator
     */
    protected function getFileValidator($postData)
    {
        $rules = [
          'file'=>'mines:xls,xlsx|max:2048'
        ];

        return Validator::make($rules, $postData);
    }

    /**
     * 跟新列表信息，提交的字段：
     *  name: 列表的名字,
     *  description: 列表的简介
     *  absent_student: 某次缺勤学生的id
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        $target = Callname_List::findOrFail($id);

        $updateValues = ['name', 'description'];
        $putData = [];
        foreach($updateValues as $curr){
            if( Input::get($curr, null) ){
                $putData[$curr] = Input::get($curr);
            }
        }

        $target->update($putData);

        $absentStudents = Input::get('absent_student', null);
        if( $absentStudents ){
            Callname_Student::markAbsentStudents($id, $absentStudents);
        }

        return Response::make('', 200);

    }

    /**
     * 查询指定的点名列表.
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式：
     * {
     *  "id": "主键id",
     *  "description": "相关描述",
     *  "creater_id": "创建者id",
     *  "created_at": "创建时间",
     *  "updated_at": "更新时间",
     *  "students" :[
     *      {
     *          "id": "id",
     *          "name": "姓名",
     *          "number": "学号"
     *      },
     *      //注意是个数组...
     * }
     */
    public function show($id)
    {
        $targetList = $this->getListById($id);

        $resp = $targetList->toArray();
        $resp['students'] = $targetList['student']->toArray();

        return Response::json($resp);
    }

    /**
     * 删除列表.
     *
     * @param $id
     * @return \Illuminate\Http\Response
     * @throws Exception
     */
    public function destroy($id)
    {
        $targetList = $this->getListById($id);

        $targetList->delete();

        return Response::make('', 200);
    }

    /**
     * 按id查找自定的点名列表，注意只有创建者才可以查看.
     *
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    protected function getListById($id)
    {
        return Callname_List::where('id', $id)
            ->where('creater_id', Auth::user()['id'])
            ->firstOrFail();
    }

}